const express = require("express");
const {findid} = require("../handleUser");

const router = new express.Router();

router.use((request,response,next)=>{

    //获取用户id
    let userID = response.cookie.get("userID");

    //用户没有登录，userID没有值
    if(!userID){
        next();
        return;
    }

    findid(userID)
    .then(
        (result)=>{
            response.islogin = true;
            response.username = result.username;
            next();
        },
        ()=>{
            response.islogin = false;
            next();
        }
    )
})

router.get("/",(request,response)=>{
    response.render("index",{
        islogin: response.islogin,
        username: response.username
    });
})

router.get("/rsuccess",(request,response)=>{
    response.render("register");
})

router.get("/lsuccess",(request,response)=>{
    response.render("login");
})

router.get("/logout",(request,response)=>{
    //清除cookie
    response.cookie.set("userID",null);
    //重定向
    response.redirect("/");
})

module.exports = router;